package com.example.mr5.money.main.express;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mr5.money.R;
import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.model.ExpressRecord;
import com.example.mr5.money.util.DatabaseHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExpressActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private EditText expressName;
    private EditText expressNum;
    private ImageView arrow;
    private ListView recordListView;
    private PopupWindow popupWindow;
    private LinearLayout spinnerLinear;
    private Button query;
    private List<String> expressName1List;
    private List<String> expressName2List;
    private int position = -1;//选择快递公司列表的位置
    private List<ExpressRecord> expressRecordList;
    private DatabaseHelper helper;
    private SQLiteDatabase db;
    private final static int REQUEST_CODE = 100;
    private final static int RESULT_CODE = 101;
    private ExpressRecordAdapter adapter;
    private AlertDialog dialog;
    private Window window;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_express);
        setTitle(getResources().getString(R.string.express));
        android.support.v7.app.ActionBar bar = getSupportActionBar();
        bar.setDisplayHomeAsUpEnabled(true);

        initData();
        initView();
    }

    private void initView() {
        expressName = (EditText) findViewById(R.id.express_name);
        expressNum = (EditText) findViewById(R.id.express_num);
        arrow = (ImageView) findViewById(R.id.arrow);
        spinnerLinear = (LinearLayout) findViewById(R.id.spinner_linear);
        arrow.setOnClickListener(this);
        query = (Button) findViewById(R.id.query);
        query.setOnClickListener(this);

        recordListView = (ListView) findViewById(R.id.express_query_result);
        adapter = new ExpressRecordAdapter(this, expressRecordList);
        recordListView.setAdapter(adapter);
        recordListView.setOnItemClickListener(this);
        recordListView.setOnItemLongClickListener(this);
    }

    private void initData(){
        expressName1List = new ArrayList<>();
        expressName2List = new ArrayList<>();
        expressName1List = Arrays.asList(getResources().getStringArray(R.array.express_name1));
        expressName2List = Arrays.asList(getResources().getStringArray(R.array.express_name2));

        expressRecordList = new ArrayList<>();
        helper = DatabaseHelper.getDBInstance(this);
        db = helper.getWritableDatabase();
        loadDataFromDB();
    }

    private void loadDataFromDB(){
        expressRecordList.clear();
        Cursor cursor = db.query(Constant.DATABASE_EXPRESS_RECORD_TABLE_NAME,null,null,null,null,null,null);
        while (cursor.moveToNext()){
            ExpressRecord expressRecord = new ExpressRecord();
            expressRecord.setCompany(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_COMPANY)));
            expressRecord.setNumber(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_NUMBER)));
            expressRecord.setId(cursor.getInt(cursor.getColumnIndex(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_ID)));
            expressRecordList.add(expressRecord);
        }
        cursor.close();
    }

    private void insertRecordIntoDB(String company,String number){
        Cursor cursor = db.query(Constant.DATABASE_EXPRESS_RECORD_TABLE_NAME,null,null,null,null,null,null);
        boolean isExist = false;
        while (cursor.moveToNext()){
            if (company.equals(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_COMPANY)))&&
                    number.equals(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_NUMBER)))){
                isExist = true;
            }
        }
        if (!isExist){
            ContentValues values = new ContentValues();
            values.put(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_COMPANY,company);
            values.put(Constant.DATABASE_EXPRESS_RECORD_TABLE_FIELD_NUMBER,number);
            db.insert(Constant.DATABASE_EXPRESS_RECORD_TABLE_NAME, null, values);
        }
    }

    private void deleteRecordFromDB(ExpressRecord record){
        db.delete(Constant.DATABASE_EXPRESS_RECORD_TABLE_NAME,"_id = ?",new String[]{record.getId()+""});
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //菜单栏返回键功能
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.arrow:
                showPopupWindow();
                break;
            case R.id.query:
                if (TextUtils.isEmpty(expressName.getText().toString()) || TextUtils.isEmpty(expressNum.getText().toString())){
                    Toast.makeText(ExpressActivity.this,"快递公司或订单号不能为空！",Toast.LENGTH_LONG).show();
                    return;
                }else {
                    if(isConn(ExpressActivity.this)){
                        Intent intent = new Intent(ExpressActivity.this,QueryResultActivity.class);
                        intent.putExtra("name",expressName.getText().toString());
                        intent.putExtra("num",expressNum.getText().toString());
                        startActivityForResult(intent,REQUEST_CODE);
                    }else {
                        Toast.makeText(ExpressActivity.this,"无网络连接，请检查网络后重试！",Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    private void showPopupWindow() {
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popupwindow_spinner, null, false);
        ListView spinnerList = (ListView) popupWindow_view.findViewById(R.id.spinner_list);
        spinnerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, expressName1List));
        spinnerList.setOnItemClickListener(this);
        popupWindow = new PopupWindow(popupWindow_view, spinnerLinear.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        popupWindow.setAnimationStyle(R.style.popWindowAnimation);//设置弹出和消失的动画
        popupWindow.setFocusable(true);// 取得焦点
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
//        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow.showAsDropDown(spinnerLinear);

        // 点击窗体内其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                return false;
            }
        });

        //设置消失的监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindow = null;
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.spinner_list){
            expressName.setText(expressName1List.get(position));
            this.position = position;
            popupWindow.dismiss();
        }else if (parent.getId() == R.id.express_query_result){
            Intent intent = new Intent(ExpressActivity.this,QueryResultActivity.class);
            intent.putExtra("name",expressRecordList.get(position).getCompany());
            intent.putExtra("num",expressRecordList.get(position).getNumber());
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            if (data.getBooleanExtra("save",false)){
                insertRecordIntoDB(expressName.getText().toString(), expressNum.getText().toString());
                loadDataFromDB();
                adapter.notifyDataSetChanged();
            }
        }
    }

    public static boolean isConn(Context context){
        boolean bisConnFlag=false;
        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if(network!=null){
            bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showDialog(expressRecordList.get(position));
        return true;
    }

    private void showDialog(final ExpressRecord record) {
        dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        window = dialog.getWindow();
        window.setContentView(R.layout.dialog_delete_item);
        final TextView dialogTitle = (TextView) window.findViewById(R.id.dialog_title);
        final TextView deleteText = (TextView) window.findViewById(R.id.delete_text);
        final TextView deleteContent = (TextView) window.findViewById(R.id.delete_content);
        dialogTitle.setText("删除记录");
        deleteContent.setText("");
        deleteText.setText("是否删除该记录？");

        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteRecordFromDB(record);
                loadDataFromDB();
                adapter.notifyDataSetChanged();
                dialog.dismiss();
                dialog = null;
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialog = null;
            }
        });
    }
}
